﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace BuildCode.Models
{
    public class ConfigHelper
    {
        private string defaultFilePath = AppDomain.CurrentDomain.BaseDirectory + "Model";
        private string configFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml";
        public XmlDocument Doc = new XmlDocument();

        public void InitConfig()
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            XmlElement root = doc.CreateElement("Config");
            doc.AppendChild(root);
            XmlElement columns = doc.CreateElement("RemoveColumns");
            root.AppendChild(columns);
            string[] cols = new string[] 
            {
                "CREATEDATE", "CREATEUSER",
                "UPDATEDATE", "UPDATEUSER", "DELDATE", "DELUSER", "EXT1", "EXT2",
                "EXT3","EXT4","EXT5", "ORGANIZATIONID","ORGID", "TENANTID","ISDELETE","DELETEUSER"
            };
            foreach (string col in cols)
            {
                XmlElement spa = doc.CreateElement("Column");
                spa.InnerText = col;
                columns.AppendChild(spa);
            }
            XmlElement connection = doc.CreateElement("ConnectionStrings");
            root.AppendChild(connection);
            XmlElement connStr = doc.CreateElement("add");
            connStr.SetAttribute("name", "Oracle");
            connStr.SetAttribute("connectionString", "Data Source=127.0.0.1:1521/ORCL;Persist Security Info=True;User ID=sa;Password=sa;");
            connStr.SetAttribute("providerName", "System.Data.OracleClient");
            connStr.SetAttribute("dataBaseName", "");
            connection.AppendChild(connStr);
            XmlElement connStr2 = doc.CreateElement("add");
            connStr2.SetAttribute("name", "SqlServer");
            connStr2.SetAttribute("connectionString", "Data Source=127.0.0.1;Initial Catalog=master;User Id=sa;Password=sa;Connect TimeOut=6000;Persist Security Info=True;");
            connStr2.SetAttribute("providerName", "System.Data.SqlClient");
            connStr2.SetAttribute("dataBaseName", "");
            connection.AppendChild(connStr2);
            XmlElement filePath = doc.CreateElement("FilePath");
            filePath.SetAttribute("Path", defaultFilePath);
            root.AppendChild(filePath);
            doc.Save(configFileName);
        }

        public void AddConnection(string connectionString, string providerName,string dataBaseName = "")
        {
            CheckConfig();
            XmlNode xn = Doc.SelectSingleNode("/Config/ConnectionStrings");
            XmlElement conn = Doc.CreateElement("add");
            string name = connectionString.Substring(connectionString.IndexOf("Data Source="));
            name = name.Substring(12);
            name = name.Substring(0, name.IndexOf(';'));
            conn.SetAttribute("name", name);
            conn.SetAttribute("connectionString", connectionString);
            conn.SetAttribute("providerName", providerName);
            conn.SetAttribute("dataBaseName", dataBaseName);
            bool flag = false;
            if (xn.ChildNodes.Count > 0)
            {
                foreach (XmlNode node in xn.ChildNodes)
                {
                    if (node.Attributes["connectionString"].Value==connectionString)
                    {
                        flag = true;
                        if (node != xn.FirstChild)
                        {
                            xn.RemoveChild(node);
                            xn.InsertBefore(conn, xn.FirstChild);
                        }
                    }
                }
                if (!flag) xn.InsertBefore(conn,xn.FirstChild);
            }
            else xn.AppendChild(conn);
            Doc.Save(configFileName);
        }

        public List<Tuple<string, string, string>> ReadConnection()
        {
            CheckConfig();
            List<Tuple<string,string, string>> list = new List<Tuple<string, string, string>>();
            XmlNodeList xnl = Doc.SelectNodes("/Config/ConnectionStrings/add");
            if (xnl.Count > 0)
            {
                foreach (XmlNode node in xnl)
                {
                    //string conn = node.Attributes["providerName"].Value + "|" + node.Attributes["connectionString"].Value;
                    list.Add(Tuple.Create(node.Attributes["providerName"].Value, node.Attributes["connectionString"].Value, node.Attributes["dataBaseName"].Value));
                } 
            }
            return list;
        }

        public void AddNameSpaces(string[] columns)
        {
            CheckConfig();
            columns = columns.Distinct().ToArray();
            XmlNode xn = Doc.SelectSingleNode("/Config/RemoveColumns");
            xn.RemoveAll();
            foreach (string space in columns)
            {
                XmlElement node = Doc.CreateElement("Column");
                node.InnerText = space;
                xn.AppendChild(node);
            }
            Doc.Save(configFileName);
        }

        public List<string> ReadRemoveCols()
        {
            CheckConfig();
            List<string> lst = new List<string>();
            XmlNodeList xnl = Doc.SelectNodes("/Config/RemoveColumns/Column");
            if (xnl.Count > 0)
            {
                foreach (XmlNode node in xnl)
                {
                    lst.Add(node.InnerText);
                }
            }
            return lst;
        }

        public void UpdateFilePath(string path)
        {
            CheckConfig();
            XmlNode xn = Doc.SelectSingleNode("/Config/FilePath");
            xn.Attributes["Path"].Value = path;
            Doc.Save(configFileName);
        }

        public string ReadFilePath()
        {
            CheckConfig();
            XmlNode xn = Doc.SelectSingleNode("/Config/FilePath");
            string path = xn.Attributes["Path"].Value;
            return path;
        }

        public void CheckConfig()
        {
            if (!File.Exists(configFileName))
            {
                InitConfig();
            }
            Doc.Load(configFileName);
        }
    }
}
